<template>
  <div>
    <el-drawer
      title="新增角色"
      v-model="visable"
      direction="rtl"
      size="30%"
      style="max-width: 500px;"
    >
      <div class="bs-dialog">
        <el-form
          ref="addRef"
          :model="dialogFormData"
          :rules="dialogFormRules"
          label-width="auto"
          style="width: 99%;padding-left: 10px;"
        >
          <el-form-item label="角色名称:" prop="roleName">
            <el-input v-model="dialogFormData.roleName" placeholder="请输入用户名称" clearable />
          </el-form-item>
          <el-form-item label="父角色:" prop="parentRoleId">
            <el-tree-select
              v-model="dialogFormData.parentRoleId"
              :data="roleData"
              filterable
              :props="roleTreeProps"
              :check-strictly="true"
              clearable
            />
          </el-form-item>
          <el-form-item label="菜单权限:" prop="rightsIdList">
            <div style="text-align: left;">
              <el-checkbox v-model="expandAll" @change="expandEvent">展开全部/折叠全部</el-checkbox>
              <el-checkbox v-model="selectAll" @change="selectEvent">全选/全不选</el-checkbox>
            </div>
            <div style="border: solid 1px gainsboro;border-radius: 3px;padding:10px;max-height: 60vh;overflow-y: scroll;">
              <el-tree
                ref="treeRef"
                v-model="dialogFormData.parentRightsId"
                show-checkbox
                :data="treeData"
                node-key="rightsId"
                :render-after-expand="false"
                style="width: 100%"
                :props="defaultProps"
                :check-on-click-node="true"
                :default-expanded-keys="expandedAllKeys"
                @check="menuCheck"
              />
            </div>
          </el-form-item>
        </el-form>
        <div class="bs-dialog-footer" style="position: absolute;bottom: 20px;right: 20px;">
          <el-button  size="small" @click="visable = false"> 取消 </el-button>
          <el-button  size="small" type="primary" @click="save"> 保存 </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listAllRole, addRole } from '@/api/system/role'
import { listAll } from '@/api/system/menu'
export default {
  data() {
    return {
      treeData: [], // 菜单列表
      treeDataBak: [], // 备份数据
      expandAll: false, // 展开所有
      selectAll: false, // 全选
      expandedAllKeys: [],
      treeIds: [], // 所有树节点ID
      defaultProps: {
        children: 'children',
        label: 'rightsName',
        value: 'rightsId'
      },
      visable: false,
      dialogFormData: {
        roleName: '',
        parentRoleId:'',
        rightsIdList: []
      },
      dialogFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: ['blur', 'change'] },
          { min: 3, max: 20, message: '3~20字符以内', trigger: ['blur', 'change'] }
        ]
      },
      roleData:[], // 角色列表
      roleTreeProps: {
        children: 'children',
        label: 'roleName',
        value: 'roleId'
      }
    }
  },
  methods: {
    openModal() {
      this.visable = true
      this.$nextTick(() => {
        this.$refs['addRef'].resetFields()
        listAll({}).then(res => {
          if (res.code === 1) {
            this.treeData = res.data
            this.treeDataBak = [...res.data]
            this.getAllNodeId(res.data)
          }
        })
        listAllRole({}).then(res=>{
          if (res.code==1) {
            this.roleData = res.data
            this.roleData.unshift({'roleId':'0','parentRoleId':'0','roleName':'无','children':[]})
          }
        })
      })
    },
    // 获取所有树节点id
    getAllNodeId(treeNodes) {
      treeNodes.forEach(item => {
        this.treeIds.push(item.rightsId)
        if (item.children && item.children.length > 0) {
          this.getAllNodeId(item.children)
        }
      })
    },
    // 保存
    save() {
      this.$refs['addRef'].validate((valid) => {
        if (valid) {
          addRole(this.dialogFormData).then(res => {
            if (res.code == 1) {
              this.$message.success('操作成功')
              this.visable = false
              // 刷新父组件中的表格数据
              this.$emit('flushTable', {})
            } else {
              this.$message.error(res.msg)
            }
          }).catch((error) => {
          })
        }
      })
    },
    /**
     * 菜单权限点击事件
     * @param {*} currentNode   点击的当前节点
     * @param {*} selectedNodes 选中的节点对象
     */
    menuCheck(currentNode, selectedNodes) {
      this.dialogFormData.rightsIdList = selectedNodes.checkedKeys
    },
    // 点击展开/收起
    expandEvent(val) {
      this.expandAll = val
      if (val === true) {
        this.expandedAllKeys = [...this.treeIds]
      } else {
        // 收起, 先把tree数据置空, 再赋值
        this.treeData = []
        this.expandedAllKeys = []
        // 必须放在
        this.$nextTick(() => {
          this.treeData = this.treeDataBak
        })
      }
    },
    // 全选/非全选
    selectEvent(val) {
      this.selectAll = val
      if (val === true) {
        this.$refs.treeRef.setCheckedKeys([...this.treeIds])
        this.dialogFormData.rightsIdList = [...this.treeIds]
      } else {
        this.selectAllKeys = []
        this.$refs.treeRef.setCheckedKeys([])
        this.dialogFormData.rightsIdList = []
      }
    }

  }
}
</script>
<style scoped>
  /deep/.el-form-item__content {
    display: inline-block;
  }
  /deep/.el-drawer__title {
    text-align: left;
  }
</style>
